equi <- function(p1, p2, n1, n2, alpha=0.05){
  tmp <- qnorm(1-alpha) * sqrt(p1*(1-p1)/n1 + p2*(1-p2)/n2)
  c1 <- p1 - p2 - tmp
  c2 <- p1 - p2 + tmp
  ci <- c(c1, c2)
  return(ci)
}

n.for.equi <- function(p, sig.diff, k=1, alpha=0.05, beta=0.2){
  n1 <- (p*(1-p))*(1+1/k)*(qnorm(1-alpha)+qnorm(1-beta))^2 / (sig.diff)^2
  n2 <- n1 * k
  
  n <- c(n1, n2)
  names(n) <- c("n1", "n2")
  return(n)
}

## Sample size for equivalent trial
n.for.equi.2p <- function (p, sig.diff, alpha=.05, power=.8 ) {
  n <- (qnorm(alpha/2) + qnorm(1-power))^2 * 2*p*(1-p)/sig.diff^2
  n <- trunc(n) + 1
  table1 <- cbind(p, n, sig.diff, alpha, power)
  colnames(table1)[colnames(table1)=="alpha"] <- "alpha"
  colnames(table1)[colnames(table1)=="power"] <- "power"
  colnames(table1)[colnames(table1)=="sig.diff"] <- "sig.diff"
  returns <- list(p=p, n=n, sig.diff=sig.diff, alpha=alpha, power=power,  
                  table = as.data.frame(table1))
  class(returns) <- c("n.for.equi.2p", "list")
  returns
}

## print n.for.equi.2p
print.n.for.equi.2p <- function(x, ...){
  if(nrow(x$table) < 6){
    cat("\n")
    cat("Estimation of sample size for testing Ho: p1==p2==p", "\n")
    cat("Assumptions:", "\n", "\n")
    cat("     alpha =", x$alpha, "\n")
    cat("     power =", x$power, "\n")
    cat("         p =", x$p, "\n")
    cat("  sig.diff =", x$sig.diff, "\n", "\n")
    cat("Estimated required sample size:", "\n", "\n")
    cat("         n =",x$n,"\n")
    cat("   Total n =",x$n*2,"\n","\n")
  }else{
    cat("Assumptions:", "\n", "\n")
    if(length(x$alpha)==1) cat("     alpha =", x$alpha, "\n")
    if(length(x$power)==1) cat("     power =", x$power, "\n")
    if(length(x$ratio)==1) cat("     n2/n1 =", x$ratio, "\n")
    cat("\n")
    print(x$table)
  }
}

